package org.microservice.gateway.fallback;

import com.alibaba.fastjson.JSON;
import com.netflix.hystrix.exception.HystrixTimeoutException;
import lombok.extern.slf4j.Slf4j;
import org.microservice.common.util.R;
import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketTimeoutException;

/**
 * Created with IntelliJ IDEA.
 * User: 齐丹枫
 * Date: 2018/6/21
 * Time: 10:52
 * To change this template use File | Settings | File Templates.
 * Description:
 */
@Slf4j
@Component
public class CustomFallbackProvider implements FallbackProvider{


    @Override
    public ClientHttpResponse fallbackResponse(Throwable throwable) {
        Throwable cause = throwable.getCause();
        log.error(throwable.toString());
        if (cause.getCause() instanceof SocketTimeoutException || throwable instanceof HystrixTimeoutException) {
            R r = R.error("连接超时，请稍后重试");
            return response(HttpStatus.GATEWAY_TIMEOUT,JSON.toJSONString(r));
        }else {
            R r = R.error("服务暂时不可用，请稍后重试");
            return response(HttpStatus.INTERNAL_SERVER_ERROR,JSON.toJSONString(r));
        }
    }

    @Override
    public String getRoute() {
        return "*";
    }

    @Override
    public ClientHttpResponse fallbackResponse() {
        return null;
    }



    private ClientHttpResponse response(final HttpStatus status,String body) {
        return new ClientHttpResponse() {
            @Override
            public HttpStatus getStatusCode() throws IOException {
                return status;
            }

            @Override
            public int getRawStatusCode() throws IOException {
                return status.value();
            }

            @Override
            public String getStatusText() throws IOException {
                return status.getReasonPhrase();
            }

            @Override
            public void close() {
            }

            @Override
            public InputStream getBody() throws IOException {

                return new ByteArrayInputStream(body.getBytes("utf-8"));
            }

            @Override
            public HttpHeaders getHeaders() {
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
                return headers;
            }
        };


    }


}
